local configData = {
    
}

function configData:Init()
    
end

function configData.load(name)
	return require(name)
end

function configData.setKey(cfg_data,key,force)
    if key=="id" and (not force) then
    	return cfg_data
    else
        local temp={}
        for i, data in pairs(cfg_data) do
            temp[data[key]]=data
        end
        return temp
    end
end

function configData.setKeys(cfg_data,...)
    local temp={}
    local arg={...}
	for _, data in ipairs(cfg_data) do
	    local cdata=temp
		for __, key in ipairs(arg) do
		    if __==#arg then
		    	cdata[data[key]]=data
		    else
                cdata[data[key]]=cdata[data[key]] or {}
                cdata=cdata[data[key]]
		    end
		end
	end
	return temp
end
--repeat key 
function configData.setArray(cfg_data,key)
	local temp={}
	for _, data in pairs(cfg_data) do
		local sub=temp[data[key]] or {}
        temp[data[key]]=sub
		table.insert(sub,data)
	end
	return temp
end

function configData.setTypeArray(cfg_data,type_key,id_key)
	local temp={}
    for _,data in pairs(cfg_data) do
        local type=data[type_key]
        local id=data[id_key]
        local type_array=temp[type] or {}
        local id_array=type_array[id] or {}
        table.insert(id_array,data)
        temp[type]=type_array
        type_array[id]=id_array
    end
    return temp
end

setmetatable(configData , {
	__index = function(self, name)
        print("config_data name:"..name)
		local value = configData.load(name)

        if name == "cfg_npc" then
            value =configData.setKey(value,"npcid") 
        elseif name == "cfg_err" or name == "cfg_city_buy" or name == "cfg_items" then
            value =configData.setKey(value,"id",true) 
        elseif name == "name" then
            value =configData.setTypeArray(value,"sex","whole") 
        elseif name == "cfg_city_distance" then
            value =configData.setKeys(value,"cityid","targetid") 
        end

        self[name] = value
		return value
	end
})

return configData